package com.jp.refreshlocalcacheserver.net.netty.message;

import com.jp.refreshlocalcacheserver.net.netty.NettyRequest;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: jipeng
 * @Description:
 * @Date: Created in 2020/5/14 18:18
 */
@Service
public class RequestMessageRegistry implements InitializingBean {

    @Resource
    private ApplicationContext applicationContext;

    private Map<Integer,RequestMessage> mapRequestMessages = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Object> mapBeans = applicationContext.getBeansWithAnnotation(NettyRequest.class);

        Iterator<Object> beans = mapBeans.values().iterator();

        Object obj;
        while(beans.hasNext()){
            obj = beans.next();
            Annotation[] annotations =  obj.getClass().getAnnotations();
            for (Annotation an : annotations){
                if(an instanceof NettyRequest){
                    NettyRequest request = (NettyRequest)an;
                    RequestMessage rm = (RequestMessage)obj;

                    mapRequestMessages.put(request.msgId(),rm);
                }
            }
        }
    }

    /**
     * 获取 RequestMessage
     * @param msgId
     * @return
     */
    public RequestMessage getRequestMessage(int msgId){
        return mapRequestMessages.get(msgId);
    }


    public RequestMessage newRequestMessage (int msgId)
            throws CloneNotSupportedException {
        RequestMessage rm = mapRequestMessages.get(msgId);
        if (rm != null) {
            return rm.clone();
        }
        return null;
    }
}
